from openai import OpenAI
import time

'''
https://api.chatanywhere.tech/#/ ChatAnywhere API 用量查询
API文档（可在线测试）: https://chatanywhere.apifox.cn
'''

with open('CHATANYWHERE_KEY', 'r', encoding='utf-8') as file:
    api_key = file.read()
client = OpenAI(api_key=api_key, base_url='https://api.chatanywhere.tech/v1')


def get_response(prompt):
    response = client.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=[
            {"role": "user", "content": prompt}
        ]
    )
    return response.choices[0].message.content


def get_response_stream(prompt, times=100):
    response = client.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=[
            {"role": "user", "content": prompt}
        ],
        stream=True
    )
    times = times if 0 < times <= 100 else 20
    for chunk in response:
        time.sleep(1 / times)
        content = chunk.choices[0].delta.content
        if content:
            content = content.replace('\n\n', '\n')
            yield content


if __name__ == '__main__':
    for chunk in get_response_stream(prompt='曹操', times=20):
        print(chunk, end='', flush=True)
